package cn.tedu.sp10.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {
//前置,后置,路由,错误处理
    @Override
    public String filterType(){
        //return "pre";
        return FilterConstants.PRE_TYPE;
    }

    //顺序号
    @Override
    public int filterOrder(){
        return 6;
    }

    //针对当前这次请求,是否要执行过滤代码
    @Override
    public boolean shouldFilter(){
        /**
         * 如果请求商品,执行过滤
         * 如果请求用户或订单,跳过过滤
         * */
        //获取请求上下文的对象
        RequestContext ctx=RequestContext.getCurrentContext().getCurrentContext();
        //获取调用的服务id
       String serviced=(String) ctx.get(FilterConstants.SERVICE_ID_KEY);

        return "item-service".equalsIgnoreCase(serviced);
    }

    //过滤代码
    public Object run() throws ZuulException{
        //获取request对象
        RequestContext ctx=RequestContext.getCurrentContext().getCurrentContext();
        HttpServletRequest request=ctx.getRequest();
        //接收token参数
        String token=request.getParameter("token");
        //如果没有token
        if(StringUtils.isBlank(token)){
            //此设置会阻止请求被路由到后台微服务
            ctx.setSendZuulResponse(false);
            //向客户端的响应
            ctx.setResponseStatusCode(200);
            ctx.setResponseBody(JsonResult.err().code(JsonResult.NOT_LOGIN).toString());
        }
        return null;
    }
}
